const event = require('../../../../utils/event.js')
const common = require('../../../../common/index')
//获取应用实例
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tab: {}, //tab组件里的值
    limit: 0,
    chatList: [
      {
        createTime: 1718933629000,
        entId: 0,
        id: "83",
        lastMessage: "cs",
        lastTime: "2024-06-24 09:06:06",
        ueDel: false,
        ueId: "949968616440549376",
        ueName: "",
        ueOpen: false,
        uePortrait: "",
        ueSex: "",
        ueUserType: 0,
        unreadNum: 0,
        urDel: false,
        urId: "963218904075198464",
        urName: "",
        urOpen: false,
        urPortrait: "",
        urSex: "0",
        urUserType: 0
      },
      {
        createTime: 1719192325000,
        entId: 0,
        id: "84",
        lastMessage: "cs",
        lastTime: "2024-06-24 09:06:06",
        ueDel: false,
        ueId: "949968616440549376",
        ueName: "",
        ueOpen: false,
        uePortrait: "",
        ueSex: "",
        ueUserType: 0,
        unreadNum: 0,
        urDel: false,
        urId: "948857668912893952",
        urName: "何晓峰",
        urOpen: false,
        urPortrait: "",
        urSex: "1",
        urUserType: 0
      }
    ],
    lockReconnect: true,
    handleClose: false,
    userId: wx.getStorageSync("userId"),
    count: [0, 0]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.handleSetTabbar()
  },

  // 初始化聊天链接
  initEventHandle(){
    let that = this
    wx.onSocketMessage((res) => {
      let data = JSON.parse(res.data)
      console.log(data,123123)
      that.data.chatList.forEach(e => {
        if(e.id === data.roomId) {
          console.log(e)
          data.id = data.roomId
          data.ueId = e.ueId
          data.urId = e.urId
          data.ueName = e.ueName
          data.urName = e.urName
          data.lastMessage = data.content
          data.lastTime = data.createTime
          data.unreadNum = e.unreadNum + 1
          that.data.chatList.splice(that.data.chatList.indexOf(e),1,data)
        }
      });
      this.setData({
        chatList: that.data.chatList
      })
      console.log(that.data.chatList)
    })
    wx.onSocketOpen(()=>{
      console.log('WebSocket连接打开')
      let data = {roomId:null, receiverId:null, senderId:null, content:'维持连接',}
      that.data.timeoutObj = setInterval(() => {
        wx.sendSocketMessage({
          data: JSON.stringify(data),
          success(){
            console.log("维持连接");
          }
        });
      }, 10000);
    })
    wx.onSocketError((res)=>{
      console.log('WebSocket连接打开失败')
      this.reconnect()
    })
    wx.onSocketClose((res)=> {
      console.log('WebSocket 已关闭！')
      console.log(this.data.handleClose)
      clearTimeout(this.data.timeoutObj);

      if(!this.data.handleClose) {
        console.log('jinlai')
        this.setData({lockReconnect: false})
        this.reconnect()
      }
    })
  },

  linkSocket(){
    let that = this
    let userId = wx.getStorageSync('userId')
    this.sockTack = wx.connectSocket({
      url: 'wss://ggjytest.qxnrcsc.com/jyfw/qzzpapi/chater/laborerWebsocket/socket/chatList/'+ userId, // 正式
      header: {
        'Authorization': wx.getStorageSync('ticket'),
      },
      success() {
        that.initEventHandle()
      }
    })
  },

  // 重新连接
  reconnect(){
    if (this.lockReconnect) return;
    this.lockReconnect = true;
    clearTimeout(this.timer)
    if (this.data.limit<12){
      this.timer = setTimeout(() => {
        console.log('重连2')
        this.linkSocket();
        this.lockReconnect = false;
      }, 5000);
      this.setData({
        limit: this.data.limit+1
      })
    }
  },

  // 加载聊天室列表
  getCartList() {
    const userType = wx.getStorageSync("userType")
    wx.showLoading({ title: '加载中' })
    console.log(userType)
    const data = {
      userType: userType
    }
    wxReq.loadChatRoomList(data).then(res => {
      wx.hideLoading()
      console.log(res,11)
      this.setData({
        chatList: res.data
      })
      this.linkSocket()
      if(this.data.chatList.length > 0) {
        this.setData({
          isShowBottom: true,
          noResult: false,
        })
      } else {
        this.setData({
          isShowBottom: false,
          noResult: true,
        })
      }
    }, err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },

  /**
   * 检测网络
   */
  checkNetWork() {
    var that = this;
    wx.onNetworkStatusChange(function (res) {
      that.setData({
        isNetwork: res.isConnected,
        questionDisable: !res.isConnected,
        serviceDisable: !res.isConnected,
      })
      if (!res.isConnected) {
        that.toastComponent.showToastComponent("网络断开,部分功能将无法使用！")
      } else {
        that.toastComponent.showToastComponent("已连上" + res.networkType.toLocaleUpperCase())
        if (!that.data.city) {
          that.getLocation()
        }
      }
    })
  },

  // 跳转聊天
  goChat(e) {
    console.log()
    const item = e.currentTarget.dataset.item
    const userType = wx.getStorageSync('userType')
    wx.navigateTo({
      url: '/package1/pages/views/jobTab/chat/chat?ueId='+ item.ueId + '&urId=' + item.urId +'&userType='+userType,
    })
  },

  handleSetTabbar(userType) {
    if (userType == 1 || userType == 2) {
      this.setData({
        ['tab.tab2name']:'人才',
        ['tab.isShow']: true,
      })
    } else if (userType == 4) {
      this.setData({
        ['tab.isShow']: false,
      })
    } else {
      this.setData({
        ['tab.tab2name']:'消息',
        ['tab.isShow']: true,
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})